package com.ruoyi.binance.api;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;

public class AccountApi {

    public static BigDecimal getUSDTBalance() {
        JSONArray balances = account();
        for (int i = 0; i < balances.size(); i++) {
            JSONObject balance = balances.getJSONObject(i);
            if ("USDT".equals(balance.getString("asset"))) {
                return balance.getBigDecimal("free");
            }
        }
        return new BigDecimal("0");
    }

    public static JSONArray getAccountByCode(String code) {
        JSONArray balances = account();
        for (int i = 0; i < balances.size(); i++) {
            JSONObject balance = balances.getJSONObject(i);
            if (code.equals(balance.getString("asset"))) {
                JSONArray objects = new JSONArray();
                objects.add(balance);
                return objects;
            }
        }
        return new JSONArray();
    }

    public static JSONArray account() {
        LinkedHashMap<String, Object> paramMap = new LinkedHashMap<>();
        paramMap.put("omitZeroBalances", true);
        paramMap.put("recvWindow", Config.RECV_WINDOW);
        paramMap.put("timestamp", System.currentTimeMillis());
        paramMap.put("signature", SignatureUtils.getSignature(paramMap));

        String body = HttpRequest.get(Config.BASE_URL + Config.ACCOUNT_URL)
                .header("X-MBX-APIKEY", Config.API_KEY)
                .form(paramMap)
                .timeout(20000)//超时，毫秒
                .execute().body();

        if (StringUtils.isBlank(body)) {
            throw new RuntimeException("请求网络异常！");
        }
        JSONObject entries = JSONObject.parseObject(body);
        JSONArray balances = entries.getJSONArray("balances");
        return balances == null ? new JSONArray() : balances;
    }

    public static void main(String[] args) {
        System.out.println(account());
    }
}
